public class spiralOrder {
    public int[] _spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }

        int top = 0;
        int right = matrix[0].length - 1;
        int bottom = matrix.length - 1;
        int left = 0;
        int[] res = new int[matrix.length * matrix[0].length];
        int index = 0;
        while (left <= right && top <= bottom) {
            // 向右移动
            if (left > right) {
                break;
            }
            for (int i = left; i <= right; i++) {
                res[index] = matrix[top][i];
                index++;
            }
            top++;

            // 向下移动
            if (top > bottom) {
                break;
            }
            for (int i = top; i <= bottom; i++) {
                res[index] = matrix[i][right];
                index++;
            }
            right--;
            // 向左移动
            if (left > right) {
                break;
            }
            for (int i = right; i >= left; i--) {
                res[index] = matrix[bottom][i];
                index++;
            }
            bottom--;

            // 向上移动
            if (top > bottom) {
                break;
            }
            for (int i = bottom; i >= top; i--) {
                res[index] = matrix[i][left];
                index++;
            }
            left++;
        }
        return res;

    }

    public static void main(String[] args) {
        int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        spiralOrder so = new spiralOrder();
        int[] res = so._spiralOrder(matrix);
        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i] + " ");
        }
    }
}
